package com.wb.code09集合.练习;

import java.util.*;

/**
 * @author 黄衡熙
 * @version 1.0
 */
/*
 *控制台输入一个字符串,统计字符串中每个字符出现的次数,保存到HashMap集合中， 至少使用两种不同的方式实现
 *通过排序,打印输出次数最多的前三个字符及次数
 * */
public class Test03_练习 {
    public static void main(String[] args) {
       // Test();
        Test2();

    }

    public static void Test() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入字符串：");
        String input = sc.nextLine();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : input.toCharArray()) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        System.out.println(map);
        List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - 1 - i; j++) {
                if (list.get(j).getValue() < list.get(j + 1).getValue()) {
                    Map.Entry<Character, Integer> temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
        System.out.println("出现次数最多的前3个字符：");
        int limit = Math.min(3, list.size());
        for (int i = 0; i < limit; i++) {
            Map.Entry<Character, Integer> entry = list.get(i);
            System.out.println("字符 '" + entry.getKey() + "' 出现了 " + entry.getValue() + " 次");
        }
    }
    public static void Test2() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入字符串：");
        String str = sc.nextLine();
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        System.out.println(map);
        List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - 1 - i; j++) {
                if (list.get(j).getValue() < list.get(j + 1).getValue()) {
                    Map.Entry<Character, Integer> temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
        System.out.println("出现次数最多的前3个字符：");
        int limit = Math.min(3, list.size());
        for (int i = 0; i < limit; i++) {
            Map.Entry<Character, Integer> entry = list.get(i);
            System.out.println("字符 '" + entry.getKey() + "' 出现了 " + entry.getValue() + " 次");
        }
    }
}
